package com.atzon.controller;

import com.atzon.constant.Const;
import com.atzon.model.UserFocus;
import com.atzon.service.UserService;
import com.atzon.service.impl.UserSrviceImpl;
import com.atzon.utils.StrUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

@WebServlet("/user/*")
public class UserServlet extends BaseServlet {
    private UserService userService = new UserSrviceImpl();
    public void list(HttpServletRequest request, HttpServletResponse response){
        try {
            String currentPage = request.getParameter("currentPage");
            String search = request.getParameter("search");
            int page = 1;
            if(null != currentPage){
                page = Integer.parseInt(currentPage);
            }
            if (null != search) {
                search = URLEncoder.encode(search, "utf-8");
                response.sendRedirect(request.getContextPath() + "/view/user?page=" + page + "&search=" + search);
            } else {
                response.sendRedirect(request.getContextPath() + "/view/user?page=" + page);
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }
    public void addUserFocus(HttpServletRequest req, HttpServletResponse resp){
        String focusid = req.getParameter("focusid");
        String userId = req.getSession().getAttribute("userId").toString();
        userService.addFocus(Integer.parseInt(userId),Integer.parseInt(focusid));
    }
    public void delUserFocus(HttpServletRequest req, HttpServletResponse resp){
        String focusid = req.getParameter("focusid");
        String userId = req.getSession().getAttribute("userId").toString();
        UserFocus userFocus = userService.findFocus(Integer.parseInt(userId),Integer.parseInt(focusid));
        userService.delFocus(userFocus.getId());
    }
    public void getDetail(HttpServletRequest request,HttpServletResponse response){
        try {
            String uId = request.getParameter("userId");
            String userId = request.getSession().getAttribute("userId").toString();
            if(!userId.equals(uId)){
                //不是自己查看自己，给对方被查数+1
                userService.addLook(Integer.parseInt(uId));
            }
            //之后查询数据返回给前端(带uid重定向view先)
            response.sendRedirect(request.getContextPath() + "/view/userDetail?uId="+uId);
        } catch (Exception e){
            e.printStackTrace();
        }
    }
    public void modInfo(HttpServletRequest req,HttpServletResponse resp){
        try {
            Map<String, Object> userBaseInfo = (Map<String, Object>)req.getSession().getAttribute("userBaseInfo");
            Integer userId = (Integer)userBaseInfo.get("id");
            String realName = req.getParameter("realName");
            String age = req.getParameter("age");
            String phone = req.getParameter("phone");
            String sex = req.getParameter("sex");
            String secret = req.getParameter("secret");
            System.out.println(secret);
            String dept = req.getParameter("dep");
            userService.modMyInfo(userId,realName,age,phone,sex,secret,dept);
            resp.sendRedirect(req.getContextPath() + "/view/userLook");
        } catch (Exception e){
            e.printStackTrace();
        }
    }
    public void uploadFile(HttpServletRequest request,HttpServletResponse response){
        try {
            ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
            servletFileUpload.setSizeMax(1024 * 1024 * 20L);
            try {
                String realPath= request.getSession().getServletContext().getRealPath(request.getRequestURI());
                System.out.println(realPath);
                int webapp = realPath.indexOf("webapp");
                realPath=realPath.substring(0,webapp+6);
                System.out.println(realPath);
                List<FileItem> files = servletFileUpload.parseRequest(request);
                FileItem item = files.get(0);
                String[] split = item.getName().split("\\.");
                if(split.length == 2){
                    String fileName = StrUtil.getUUID() + "." + split[1];
                    String filePath = realPath + "/upload/" + fileName;
                    System.out.println(realPath);
                    File file = new File(filePath);
                    if(!file.exists()){
                        item.write(file);
                    }
                    //下一步更新用户头像
                    String userId = request.getSession().getAttribute("userId").toString();
                    String path = "/upload/" + fileName;
                    userService.updateUserImg(Integer.parseInt(userId),path);

                    //session的头像也要更新
                    //再去后台查询用户的基本信息(并且直接保存到会话域里面)
                    Map<String, Object> map = userService.findUserBaseById(Integer.parseInt(userId));
                    request.getSession().setAttribute("userBaseInfo", map);
                    response.getWriter().write(path);
                } else {
                    response.getWriter().write("fail");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e){
            e.printStackTrace();
        }

    }
}